import { ElementRef, EventEmitter, Injector, Input, Output, Component, OnInit, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as XLSX from 'xlsx';

@Component({
    selector: 'excel-export',
    template: `
        <button
            class="btn"
            [ngClass]="'btn-' + btnColor"
            [ngClass]="{ 'only-link dropdown-item': isLink }"
            (click)="export()"
            style="margin-left: 10px"
        >
            <i *ngIf="showIcon" class="fa fa-plus"></i> {{ btnText }}
        </button>
    `,
    styles: [
        `
            .only-link {
                color: #575962 !important;
                background-color: #fff !important;
                border-color: #fff !important;
            }
        `,
        `
            .only-link:hover:not(:disabled) {
                color: #575962 !important;
                background: #f4f5f8 !important;
                text-decoration: none !important;
            }
        `
    ]
})
export class ExcelExportComponent extends AppComponentBase {
    constructor(injector: Injector, private _element: ElementRef) {
        super(injector);
    }
    @Input() btnColor = '';
    @Input() btnText = '导出';
    @Input() fileName = '模版';
    @Input() showIcon = false;
    @Input() isLink = false;
    @Input() data = [];

    export() {
        /* Generate Workbook */
        let wb = XLSX.utils.book_new();
        let ws = this.data;

        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

        /* Trigger Download with `writeFile` */
        XLSX.writeFile(wb, this.fileName + '.xlsx', { compression: true });
    }
}
